<template>
  <div class="vue3SeamlessScroll">
    <div ref="scrollRef" @click="Change">
      <slot />
    </div>
  </div>
</template>
<script>
  import {ref, nextTick, onUnmounted, watch} from 'vue'
  export default {
    name: 'vue3SeamlessScroll',
    props: {
      classOption: {
        type: Object,
        default(){
          return {
            step: 1, // 速度
            hoverStop: true, // 鼠标停止
            direction: 1, // 0 下 1 上 2 左 3 右
            setTimeout: 1000 // 延迟执行 毫秒
          }
        },
      },
      list: {
        type: Array,
        default() {
          return []
        },
        required: true
      }
    },
    emits: ['onChange'],
    setup(props, ctx) {
      const scrollRef = ref(null)
      // eslint-disable-next-line no-unused-vars
      let scroll = null
      // 初始化
      function scrollInit() {
        nextTick(() => {
          const config = Object.assign({
            step: 1, // 速度
            hoverStop: true, // 鼠标停止
            direction: 1, // 0 下 1 上 2 左 3 右
            setTimeout: 1000 // 延迟执行 毫秒
          },props.classOption)
          if(config.stop) {
            return
          }
          config.dom = scrollRef.value
          if(scrollRef.value.clientHeight > scrollRef.value.parentNode.clientHeight ||
              scrollRef.value.clientWidth > scrollRef.value.parentNode.clientWidth) {
            setTimeout(() => {
              scroll && scroll._cancle()
              // scroll = init(config)
            }, config.setTimeout)
          }
        })
      }
      watch(() => props.list, () => {
        scrollInit()
      }, {
        immediate: true,
        deep: true
      })
      watch(() => props.classOption, () => {
        scrollInit()
      }, {
        immediate: true,
        deep: true
      })
      // 点击事件
      function Change(e) {
        let ele
        function find (ele) {
          if (Object.keys(ele.dataset).length > 1) {
            return ele
          }
          if(ele.parentElement.className === 'vue3SeamlessScroll') {
            return
          }
          return find(ele.parentElement)
        }
        ele = find(e.target)
        if(ele){
          ctx.emit('onChange', ele.dataset)
        }
      }
      onUnmounted(() => {
        scroll && scroll._cancle()
        scroll = null
      })
      return {
        scrollRef,
        Change
      }
    },
  }
</script>

<style lang="scss" scoped>
.vue3SeamlessScroll {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
}
</style>